"use client";
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Loader2, CheckCircle, XCircle, Database, ArrowRight, RefreshCw, AlertTriangle } from 'lucide-react';
import { toast } from '@/components/ui/use-toast';
import { useToast } from "@/hooks/use-toast"
import { DeviceParametersDialog } from '@/components/device-parameters-dialog';
import { Device } from '@/lib/sqlite-database';

export default function SqliteManagementPage() {
  const { toast } = useToast()
  const [loading, setLoading] = useState(false);
  const [migrating, setMigrating] = useState(false);
  const [result, setResult] = useState<{ success: boolean; message: string; data?: any } | null>(null);
  const [migrationResult, setMigrationResult] = useState<{ success: boolean; message: string; data?: any } | null>(null);
  const [stats, setStats] = useState<{ name: string; count: number; devices: any[] }[] | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [testResult, setTestResult] = useState<{ success: boolean; message: string; deviceId?: string } | null>(null);
  const [diagnosisResult, setDiagnosisResult] = useState<any>(null);
  const [gapAnalysisResult, setGapAnalysisResult] = useState<any>(null);
  const [baseParamsAnalysisResult, setBaseParamsAnalysisResult] = useState<any>(null);
  const [importingCustom, setImportingCustom] = useState(false)
  const [importResult, setImportResult] = useState<{success: boolean, message: string} | null>(null)
  const [rebuilding, setRebuilding] = useState(false)
  const [rebuildResult, setRebuildResult] = useState<any>(null)
  const [rawImporting, setRawImporting] = useState(false);
  const [rawImportResult, setRawImportResult] = useState<any>(null);
  const [attrImporting, setAttrImporting] = useState(false);
  const [attrImportResult, setAttrImportResult] = useState<any>(null);
  const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
  const [isParametersDialogOpen, setIsParametersDialogOpen] = useState(false);

  // 页面加载时获取数据库状态
  useEffect(() => {
    fetchStats();
  }, []);

  const fetchStats = async () => {
    try {
      const response = await fetch('/api/sqlite-dashboard-stats');
      if (response.ok) {
        const data = await response.json();
        setStats(data.specialtyStats || []);
      }
    } catch (error) {
      console.error('获取数据库状态失败:', error);
    }
  };

  const handleImportCustomData = async () => {
    setImportingCustom(true);
    setImportResult(null);
    try {
      const response = await fetch('/api/import-custom-data', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '导入过程中发生未知错误');
      }
      setImportResult({ success: true, message: data.message });
      toast({ title: "成功", description: data.message });
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setImportResult({ success: false, message });
      toast({ title: "失败", description: message, variant: "destructive" });
    } finally {
      setImportingCustom(false);
    }
  };

  const handleMigration = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/import-data', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '数据导入过程中发生未知错误');
      }
      setMigrationResult({ success: true, message: data.message, data: { migratedCount: data.importedCount } });
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const testChineseCharacters = async () => {
    setIsLoading(true);
    setTestResult(null);
    try {
      const response = await fetch('/api/test-chinese-characters', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '中文字符测试失败');
      }
      setTestResult({ success: true, message: data.message });
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setTestResult({ success: false, message });
    } finally {
      setIsLoading(false);
    }
  };

  const handleRealSqliteMigration = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/migrate-to-real-sqlite', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.message || '修复字符编码过程中发生未知错误');
      }
      setMigrationResult({ success: true, message: data.message, data });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleResetParameterIds = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/reset-database-ids', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.message || '重置参数表ID过程中发生未知错误');
      }
      setMigrationResult({ success: true, message: data.message, data });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handlePopulateSampleData = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/populate-sample-data', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.message || '填充示例数据过程中发生未知错误');
      }
      setMigrationResult({ success: true, message: data.message, data });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleCreateClassificationTables = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/create-classification-tables', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '创建分类表过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: `成功创建设备分类专用参数表！创建了 ${data.tablesCreated} 个表`, 
        data 
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleReimportCsvParameters = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/reimport-csv-parameters', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '重新导入CSV参数表过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: data.message, 
        data 
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleFixMissingParameters = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/fix-missing-parameters', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '修复缺失参数过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: data.message, 
        data 
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
        } finally {
      setMigrating(false);
    }
  };

  const handleDiagnosis = async () => {
    setIsLoading(true);
    setDiagnosisResult(null);
    try {
      const response = await fetch('/api/diagnose-parameter-data');
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '诊断过程中发生未知错误');
      }
      setDiagnosisResult(data);
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setDiagnosisResult({ success: false, message });
        } finally {
      setIsLoading(false);
    }
  };

  const handleCleanPositionParameters = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/clean-position-parameters', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '清理位置参数过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: data.message, 
        data 
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
     };

  const handleGapAnalysis = async () => {
    setIsLoading(true);
    setGapAnalysisResult(null);
    try {
      const response = await fetch('/api/analyze-position-data-gap');
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '数据缺口分析过程中发生未知错误');
      }
      setGapAnalysisResult(data);
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setGapAnalysisResult({ success: false, message });
    } finally {
      setIsLoading(false);
    }
  };

  const handleCleanAfter1400 = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/clean-position-data-after-1400', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '清理1400行后数据过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: `${data.message} (删除 ${data.deletedCount} 行，保留 ${data.remainingCount} 行)`, 
        data 
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleReimportPositionParameters = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/reimport-position-parameters-from-excel', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '重新导入位置参数过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: `${data.message}`, 
        data 
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleRebuildSchema = async () => {
    setRebuilding(true);
    setRebuildResult(null);
    try {
      const response = await fetch('/api/rebuild-sqlite-schema', { method: 'POST' });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '重建失败');
      }
      setRebuildResult({ success: true, message: data.message });
      toast({ title: "成功", description: data.message });
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setRebuildResult({ success: false, message });
      toast({ title: "失败", description: message, variant: "destructive" });
    } finally {
      setRebuilding(false);
    }
  };

  const handleReimportNamingParameters = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/reimport-naming-parameters-from-excel', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '重新导入命名参数过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: data.message, 
        data 
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleReimportBaseParameters = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/reimport-base-parameters-from-excel', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '重新导入基础参数过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: data.message, 
        data 
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleAnalyzeBaseParameterTables = async () => {
    setIsLoading(true);
    setBaseParamsAnalysisResult(null);
    try {
      const response = await fetch('/api/analyze-base-parameter-tables');
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '分析基础参数表过程中发生未知错误');
      }
      setBaseParamsAnalysisResult(data);
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setBaseParamsAnalysisResult({ success: false, message });
    } finally {
      setIsLoading(false);
    }
  };

  const handleResetAllIds = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/reset-all-ids', {
        method: 'POST',
      });
      
      if (!response.ok) {
        throw new Error('重置ID失败');
      }

      const data = await response.json();
      toast({
        title: '重置成功',
        description: `设备表: ${data.stats.devices.count} 行，最小ID: ${data.stats.devices.minId}\n基础参数表: ${data.stats.baseParameters.count} 行，最小ID: ${data.stats.baseParameters.minId}\n位置参数表: ${data.stats.positionParameters.count} 行，最小ID: ${data.stats.positionParameters.minId}\n命名参数表: ${data.stats.namingParameters.count} 行，最小ID: ${data.stats.namingParameters.minId}`,
      });
    } catch (error) {
      toast({
        variant: 'destructive',
        title: '错误',
        description: error instanceof Error ? error.message : '未知错误',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleImportMeasurementUnits = async () => {
    setMigrating(true);
    setMigrationResult(null);
    try {
      const response = await fetch('/api/import-measurement-units', { method: 'POST' });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '导入计量单位过程中发生未知错误');
      }
      setMigrationResult({ 
        success: true, 
        message: data.message, 
        data: {
          importedCount: data.importedCount,
          totalParsed: data.totalParsed
        }
      });
      // 重新获取统计信息
      await fetchStats();
    } catch (error) {
      const message = error instanceof Error ? error.message : '与服务器通信失败';
      setMigrationResult({ success: false, message });
    } finally {
      setMigrating(false);
    }
  };

  const handleRawImport = async () => {
    setRawImporting(true);
    setRawImportResult(null);
    try {
      const response = await fetch('/api/import-raw-csv', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ directory: '06-21' }),
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.message || '导入失败');
      }
      setRawImportResult({ success: true, data });
      toast({
        title: "原始导入成功",
        description: data.message,
      });
    } catch (error: any) {
      setRawImportResult({ success: false, message: error.message });
      toast({
        title: "原始导入失败",
        description: error.message,
        variant: "destructive",
      });
    } finally {
      setRawImporting(false);
    }
  };

  const handleAttributeImport = async () => {
    setAttrImporting(true);
    setAttrImportResult(null);
    try {
      const response = await fetch('/api/import-attribute-tables', {
        method: 'POST',
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.message || '导入失败');
      }
      setAttrImportResult({ success: true, data });
      toast({
        title: "属性表导入成功",
        description: data.message,
      });
    } catch (error: any) {
      setAttrImportResult({ success: false, message: error.message });
      toast({
        title: "属性表导入失败",
        description: error.message,
        variant: "destructive",
      });
    } finally {
      setAttrImporting(false);
    }
  };

  const handleDeviceRowClick = (device: Device) => {
    setSelectedDevice(device);
    setIsParametersDialogOpen(true);
  };

  const renderDeviceTable = (devices: Device[]) => (
    <div className="overflow-x-auto">
      <table className="min-w-full divide-y divide-gray-200">
        <thead className="bg-gray-50">
          <tr>
            <th>Device ID</th>
            <th>Name</th>
            <th>Naming Table</th>
            <th>Position Table</th>
            <th>Base Params Table</th>
          </tr>
        </thead>
        <tbody className="bg-white divide-y divide-gray-200">
          {devices.filter(d => d && d.device_id).map((device) => (
            <tr key={device.id} onClick={() => handleDeviceRowClick(device)} className="hover:bg-gray-100 cursor-pointer">
              <td>{device.device_id}</td>
              <td>{device.name}</td>
              <td>{device.naming_table_id}</td>
              <td>{device.position_table_id}</td>
              <td>{device.base_params_table_id}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  return (
    <>
      <div className="container mx-auto py-8">
      <div className="mb-8">
        <h1 className="text-4xl font-bold text-primary mb-4">SQLite 数据库管理</h1>
        <p className="text-muted-foreground">管理SQLite数据库的导入、清理和维护操作</p>
        
        {/* 数据库文件信息 */}
        <div className="mt-6 p-4 bg-blue-50 rounded-lg border">
          <h3 className="text-lg font-semibold text-blue-800 mb-2">📁 数据库文件信息</h3>
          <div className="space-y-1 text-sm">
            <p><strong>SQLite数据库文件：</strong> <code className="bg-gray-100 px-2 py-1 rounded">data/delivery-management.db</code></p>
            <p><strong>JSON数据文件：</strong> <code className="bg-gray-100 px-2 py-1 rounded">data/json-database.json</code></p>
            <p><strong>说明：</strong> 系统现在使用真正的SQLite数据库（.db二进制文件），支持中文字符和并发访问</p>
            <p><strong>优势：</strong> 更好的性能、数据完整性、事务支持、无中文编码问题</p>
          </div>
        </div>
      </div>

      {/* 数据库状态 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>🔍 数据库状态检查</CardTitle>
        </CardHeader>
        <CardContent>
          {stats ? (
            <div className="space-y-4">
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                {stats.map((stat, index) => (
                  <div key={`${stat.name}-${index}`} className="text-center p-3 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-primary">{stat.count}</div>
                    <div className="text-sm text-muted-foreground">{stat.name}</div>
                  </div>
                ))}
              </div>
              
              {/* 最近添加的设备 */}
              <div className="mt-4">
                <h4 className="font-semibold mb-2">最近添加的设备（前5个）：</h4>
                <div className="max-h-32 overflow-y-auto">
                  {stats.flatMap(s => s.devices)
                    .filter(device => device && device.device_id)
                    .map((device, index) => (
                    <div key={`${device.id}-${index}`} className="text-sm p-2 border-b">
                      <span className="font-mono">{device.device_id}</span> - 
                      <span className="ml-2">{device.name}</span> - 
                      <span className="text-gray-500 ml-2">{device.specialty}</span>
                      <span className="text-xs text-gray-400 ml-2">
                        {new Date(device.created_at || '').toLocaleString()}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
              
              {/* 表ID格式检查 */}
              <div className="mt-4 p-3 bg-green-50 rounded-lg border border-green-200">
                <h4 className="font-semibold mb-2 text-green-800">📋 表ID格式验证（最新标准）</h4>
                <div className="text-sm space-y-1">
                  {stats.flatMap(s => s.devices)
                    .slice(0, 3)
                    .filter(device => device)
                    .map((device, index) => (
                    <div key={`${device.id}-${index}`} className="flex justify-between">
                      <span className="font-mono text-gray-600">{device.device_id || `设备${index + 1}`}:</span>
                      <span className="text-green-700">
                        命名表: <code className="bg-green-100 px-1 rounded">{device.naming_table_id || '未设置'}</code> | 
                        位置表: <code className="bg-green-100 px-1 rounded ml-1">{device.position_table_id || '未设置'}</code> | 
                        基本参数表: <code className="bg-green-100 px-1 rounded ml-1">{device.base_params_table_id || '未设置'}</code>
                      </span>
                    </div>
                  ))}
                </div>
                <div className="text-xs text-green-600 mt-2">
                  ✅ 正确格式：C2（命名表）、C4/C6（位置表）、C18/C20等（基本参数表）
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-4">
              <Loader2 className="h-6 w-6 animate-spin mx-auto mb-2" />
              <p>正在加载数据库状态...</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 测试区域 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>🧪 中文字符编码测试</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <Button 
              onClick={testChineseCharacters}
              disabled={isLoading}
              className="w-full"
            >
              {isLoading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-2" />
                  测试中...
                </>
              ) : (
                '测试中文字符保存'
              )}
            </Button>
            
            {testResult && (
              <div className={`p-3 rounded-lg ${testResult.success ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`}>
                <p><strong>测试结果：</strong> {testResult.message}</p>
                {testResult.deviceId && (
                  <p className="text-sm mt-1">设备ID: {testResult.deviceId}</p>
                )}
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 从CSV导入数据到数据库 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center space-x-2">
            <Database className="w-5 h-5" />
            <span>核心数据导入</span>
          </CardTitle>
          <CardDescription>
            从所有指定的CSV源文件（位于 /excel/06-21/）重新导入全部数据到SQLite数据库。
            此操作会先清空设备、参数和计量单位相关的现有数据，请谨慎使用。这是系统初始化的关键步骤。
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col items-start space-y-4">
            <Button onClick={handleImportCustomData} disabled={importingCustom}>
              {importingCustom ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
              开始导入
            </Button>
            {importResult && (
              <div className={`mt-4 p-2 rounded-md ${importResult.success ? 'bg-green-100' : 'bg-red-100'}`}>
                <div className="flex items-center gap-2">
                  {importResult.success ? <CheckCircle className="text-green-600 h-5 w-5" /> : <XCircle className="text-red-600 h-5 w-5" />}
                  <p className={`font-semibold ${importResult.success ? 'text-green-800' : 'text-red-800'}`}>
                    {importResult.message}
                </p>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 数据导入 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center space-x-2">
            <ArrowRight className="w-5 h-5" />
            <span>从CSV文件导入数据到SQLite</span>
          </CardTitle>
          <CardDescription>
            从 /excel/06-21/ 目录下的CSV源文件（设备、参数、计量单位）重新导入全部数据到SQLite数据库。
            此操作会先清空并替换现有相关表（devices, parameters, units）的数据。请谨慎操作。
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col items-start space-y-4">
            <div className="flex space-x-4 w-full">
              <Button onClick={handleMigration} disabled={loading || migrating}>
                {migrating ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    正在导入...
                  </>
                ) : (
                  '清空并从CSV导入全部设备'
                )}
              </Button>
            </div>
            
            {migrationResult && (
              <div className="mt-4 flex items-center space-x-2">
                  {migrationResult.success ? (
                    <CheckCircle className="h-5 w-5 text-green-500" />
                  ) : (
                    <XCircle className="h-5 w-5 text-red-500" />
                  )}
                  <p className={migrationResult.success ? 'text-green-600' : 'text-red-600'}>
                    {migrationResult.message}
                  {migrationResult.data?.migratedCount !== undefined && 
                    ` (总计: ${migrationResult.data.migratedCount} 个设备)`
                  }
                </p>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* SQLite数据库信息 */}
      <Card>
        <CardHeader>
          <CardTitle>SQLite 数据库结构</CardTitle>
          <CardDescription>
            新的数据库结构设计，支持实体对象和三种类型的参数表单录入。
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="p-4 border rounded-lg">
                <h4 className="font-semibold mb-2">🏭 devices (实体对象表)</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>• device_id: 设备编号</li>
                  <li>• name: 设备名称</li>
                  <li>• specialty: 专业类别</li>
                  <li>• classification_*: 分类信息</li>
                  <li>• *_table_id: 关联的参数表ID</li>
                </ul>
              </div>
              
              <div className="p-4 border rounded-lg">
                <h4 className="font-semibold mb-2">📝 naming_parameters (命名参数表)</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>• device_id: 关联设备ID (外键)</li>
                  <li>• parameter_name: 参数名称</li>
                  <li>• parameter_value: 参数值</li>
                  <li>• data_type: 数据类型</li>
                  <li>• is_required: 是否必填</li>
                </ul>
              </div>

              <div className="p-4 border rounded-lg">
                <h4 className="font-semibold mb-2">📍 position_parameters (位置参数表)</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>• device_id: 关联设备ID (外键)</li>
                  <li>• parameter_name: 参数名称</li>
                  <li>• parameter_value: 参数值</li>
                  <li>• data_type: 数据类型</li>
                  <li>• is_required: 是否必填</li>
                </ul>
              </div>

              <div className="p-4 border rounded-lg">
                <h4 className="font-semibold mb-2">⚙️ base_parameters (基础参数表)</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>• device_id: 关联设备ID (外键)</li>
                  <li>• parameter_name: 参数名称</li>
                  <li>• parameter_value: 参数值</li>
                  <li>• measurement_unit: 计量单位</li>
                  <li>• is_required: 是否必填</li>
                </ul>
              </div>
            </div>

            <div className="bg-blue-50 p-4 rounded-lg">
              <h4 className="font-semibold mb-2">✨ 主要特性：</h4>
              <ul className="text-sm space-y-1">
                <li>• 通过外键关联实现数据完整性</li>
                <li>• 支持三种类型的参数表单录入</li>
                <li>• 自动时间戳记录创建和更新时间</li>
                <li>• 索引优化提高查询性能</li>
                <li>• 级联删除确保数据一致性</li>
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="flex flex-col gap-4">
        <Button 
          variant="outline" 
          onClick={handleResetAllIds}
          disabled={loading}
        >
          {loading ? '处理中...' : '重置所有表ID'}
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>从CSV原始导入 (06-21)</CardTitle>
          <CardDescription>
            将 <code>excel/06-21</code> 目录下的所有CSV文件作为原始表格导入数据库。
            每个CSV文件会创建一个对应的数据库表，表名基于文件名，并添加 <code>raw_</code> 前缀。
          </CardDescription>
        </CardHeader>
        <CardContent>
          {rawImportResult && (
            <div className={`mt-4 p-4 rounded-md ${rawImportResult.success ? 'bg-green-100' : 'bg-red-100'}`}>
              {rawImportResult.success ? (
                <div className="flex items-center gap-2">
                  <CheckCircle className="text-green-600" />
                  <div>
                    <p className="font-bold text-green-800">导入成功</p>
                    <pre className="text-xs text-green-700 mt-2 bg-green-50 p-2 rounded">
                      {JSON.stringify(rawImportResult.data.details, null, 2)}
                    </pre>
    </div>
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <AlertTriangle className="text-red-600" />
                  <div>
                    <p className="font-bold text-red-800">导入失败</p>
                    <p className="text-sm text-red-700">{rawImportResult.message}</p>
                  </div>
                </div>
              )}
            </div>
          )}
        </CardContent>
        <CardFooter>
          <Button onClick={handleRawImport} disabled={rawImporting}>
            {rawImporting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
            开始原始导入
          </Button>
        </CardFooter>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>导入属性表 (从06-21)</CardTitle>
          <CardDescription>
            仅从 <code>excel/06-21</code> 目录导入所有以 "属性表-" 开头的CSV文件。
          </CardDescription>
        </CardHeader>
        <CardContent>
          {attrImportResult && (
            <div className={`mt-4 p-4 rounded-md ${attrImportResult.success ? 'bg-green-100' : 'bg-red-100'}`}>
              {attrImportResult.success ? (
                <div className="flex items-center gap-2">
                  <CheckCircle className="text-green-600" />
                  <div>
                    <p className="font-bold text-green-800">导入成功</p>
                    <pre className="text-xs text-green-700 mt-2 bg-green-50 p-2 rounded">
                      {JSON.stringify(attrImportResult.data.details, null, 2)}
                    </pre>
                  </div>
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <AlertTriangle className="text-red-600" />
                  <div>
                    <p className="font-bold text-red-800">导入失败</p>
                    <p className="text-sm text-red-700">{attrImportResult.message}</p>
                  </div>
                </div>
              )}
            </div>
          )}
        </CardContent>
        <CardFooter>
          <Button onClick={handleAttributeImport} disabled={attrImporting}>
            {attrImporting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
            开始导入属性表
          </Button>
        </CardFooter>
      </Card>

      {stats && (
        <Card>
          <CardHeader>
            <CardTitle>数据库统计</CardTitle>
            <CardDescription>各专业下的设备数量</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {stats.filter(s => s && s.name).map((specialty) => (
                <div key={specialty.name}>
                  <h3 className="text-lg font-semibold">{specialty.name} ({specialty.count} a..z)</h3>
                  {specialty.devices && specialty.devices.length > 0 ? (
                    renderDeviceTable(specialty.devices)
                  ) : (
                    <p className="text-sm text-gray-500">该专业下没有设备</p>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {baseParamsAnalysisResult && (
        <Card>
          <CardHeader>
            <CardTitle>基础参数表分析</CardTitle>
            <CardDescription>
              分析基础参数表的结构和内容
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <p><strong>分析结果：</strong> {baseParamsAnalysisResult.message}</p>
              {baseParamsAnalysisResult.data && (
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Device ID</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Parameter Name</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Parameter Value</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Measurement Unit</th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Is Required</th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                      {baseParamsAnalysisResult.data.map((item: any) => (
                        <tr key={item.device_id}>
                          <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{item.device_id}</td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{item.parameter_name}</td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{item.parameter_value}</td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{item.measurement_unit}</td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{item.is_required ? 'Yes' : 'No'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
    <DeviceParametersDialog
      open={isParametersDialogOpen}
      onOpenChange={setIsParametersDialogOpen}
      deviceId={selectedDevice?.id ?? null}
      deviceName={selectedDevice?.name}
    />
    </>
  );
} 